from typing import Optional


# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:

    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        """
            自己凭借感觉写的，逻辑稍差
        """
        if head is None or head.next is None:
            return head

        # 初始化变量
        ans = head.next
        left = head
        right = head.next
        pre = left

        while left and right:
            tem = right.next
            right.next = left
            left.next = tem
            left = tem

            # 如果只有省两个结点的情况
            if left and left.next:
                right = tem.next
                pre.next = right
                pre = left
    
            # 如果只剩一个结点的情况
            else:
                pre.next = left
                right = None
        return ans
